<template>
  <!-- 详情开始 -->
  <a-modal
    :maskClosable="false"
    title="成本总额"
    :width="1350"
    :bodyStyle="{
      padding: '0 24px'
    }"
    :visible="visible"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-card
      :bordered="false"
      :bodyStyle="{
        padding: '10px 24px'
      }">
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <span>
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 其他费用报销
          </span>
        <span style="float: right">
            总额：{{ otherSum }}元
        </span>
      </div>
      <div>
        <a-table
          ref="table"
          rowKey="id"
          :scroll="scrollTrigger"
          :columns="columns3"
          :dataSource="dataSource3"
          :pagination="ipagination3"
          :loading="loading3"
          class="j-table-force-nowrap"
          wrapClassName="ant-modal-cust-warp"
          @change="handleTableChange3"
          >
          <span slot="billNo" slot-scope="text, record">
            <a @click="onDetail(record)">{{text}}</a>
          </span>
        </a-table>
      </div>
      <!--         工程进度付款单 table区域-begin -->
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <span>
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 工程进度付款单
          </span>
        <span style="float: right">
            总额：{{ engineeringSum }}元
        </span>
      </div>
      <div>
        <a-table
          ref="table"
          rowKey="id"
          :scroll="scrollTrigger"
          :columns="columns2"
          :dataSource="dataSource2"
          :pagination="ipagination2"
          :loading="loading2"
          class="j-table-force-nowrap"
          wrapClassName="ant-modal-cust-warp"
          @change="handleTableChange2"
         >
         <span slot="billNo" slot-scope="text, record">
            <a @click="onDetail(record)">{{text}}</a>
          </span>
        </a-table>
      </div>
      <!--      其他费用报销 table区域-begin -->
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <span>
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 差旅费用报销
          </span>
        <span style="float: right">
            总额：{{ travelSum }}元
        </span>
      </div>
      <!--      差旅费用报销 table区域-begin -->
      <div>
        <a-table
          ref="table"
          rowKey="id"
          :scroll="scrollTrigger"
          :columns="columns"
          :dataSource="dataSource1"
          :pagination="ipagination1"
          :loading="loading1"
          class="j-table-force-nowrap"
          wrapClassName="ant-modal-cust-warp"
          @change="handleTableChange1"
          >
          <span slot="billNo" slot-scope="text, record">
            <a @click="onDetail(record)">{{text}}</a>
          </span>
        </a-table>
      </div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <span>
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 绩效提取单
          </span>
        <span style="float: right">
            总额：{{ extractionSum }}元
        </span>
      </div>
      <div>
        <a-table
          ref="table"
          rowKey="id"
          :scroll="scrollTrigger"
          :columns="columns4"
          :dataSource="dataSource4"
          :pagination="ipagination4"
          :loading="loading4"
          class="j-table-force-nowrap"
          wrapClassName="ant-modal-cust-warp"
          @change="handleTableChange4"
          >
          <span slot="billNo" slot-scope="text, record">
            <a @click="onDetail(record)">{{text}}</a>
          </span>
        </a-table>
      </div>
    </a-card>
    <template slot="footer">
      <a-button type="primary" icon="download" @click="handleExportXls('成本总额')">导出</a-button>
      <a-button @click.stop="()=>{visible=false}">关闭</a-button>
    </template>
    <ErpFinanceReimbursementPenetrate ref="reimbursementBill"></ErpFinanceReimbursementPenetrate>
    <ErpFinanceProjectProgressBillPenetrate ref="projectProgressBill"></ErpFinanceProjectProgressBillPenetrate>
    <ErpFinanceTraveBillPenetrate  ref="traveReimbursementBill"></ErpFinanceTraveBillPenetrate>
    <ErpAchievementsExtractionPenetrate  ref="erpAchievementsExtraction"></ErpAchievementsExtractionPenetrate>
  </a-modal>
</template>

<script>

  import { filterObj } from '@/utils/util';
  import { downFile,getAction } from '@/api/manage'
  import ErpFinanceReimbursementPenetrate from '@/views/scy/penetrate/ErpFinanceReimbursementPenetrate'
  import ErpFinanceProjectProgressBillPenetrate from '@/views/scy/penetrate/ErpFinanceProjectProgressBillPenetrate'
  import ErpFinanceTraveBillPenetrate from '@/views/scy/penetrate/ErpFinanceTraveBillPenetrate'
  import ErpAchievementsExtractionPenetrate from '@/views/scy/penetrate/ErpAchievementsExtractionPenetrate'
  export default {
    name: 'ErpProjectFinanceReimbursementList',
    components: {
      ErpFinanceTraveBillPenetrate,
      ErpFinanceProjectProgressBillPenetrate,
      ErpFinanceReimbursementPenetrate,
      ErpAchievementsExtractionPenetrate
    },
    props: [],
    data() {
      return {
        title: '成本总额',
        dataSource: [],
        dataSource1: [],
        dataSource2: [],
        dataSource3: [],
        dataSource4: [],
        loading1: false,
        loading2: false,
        loading3: false,
        loading4: false,
        scrollTrigger: { x: true },
        ipagination1: {
          current: 1,
          pageSize: 5,
          pageSizeOptions: ['5', '10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        ipagination2: {
          current: 1,
          pageSize: 5,
          pageSizeOptions: ['5', '10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        ipagination3: {
          current: 1,
          pageSize: 5,
          pageSizeOptions: ['5', '10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        ipagination4: {
          current: 1,
          pageSize: 5,
          pageSizeOptions: ['5', '10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        isorter: {
          column: 'checkTime',
          order: 'desc'
        },
        columns: [
        {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'单据编号',
            align:"center",
            dataIndex: 'billNo',
            scopedSlots: { customRender: 'billNo' },
            ellipsis: true
          },
          {
            title:'报销人',
            align:"center",
            dataIndex: 'proposerName',
            ellipsis: true
          },
          {
            title:'申请部门',
            align:"center",
            dataIndex: 'proposerDeptId_dictText',
            ellipsis: true
          },
          {
            title:'费用所属团队',
            align:"center",
            dataIndex: 'teamId_dictText',
            ellipsis: true
          },
          {
            title:'报销金额（元）',
            align:"center",
            dataIndex: 'reimbursementAmount',
            ellipsis: true
          },
          {
            title:'自驾公里数补助（元）',
            align:"center",
            dataIndex: 'kilometresAmount',
            ellipsis: true
          }

        ],
        columns1: [
        {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'单据编号',
            align:"center",
            dataIndex: 'billNo',
            scopedSlots: { customRender: 'billNo' },
            ellipsis: true
          },
          {
            title:'报销人',
            align:"center",
            dataIndex: 'proposerName',
            ellipsis: true
          },
          {
            title:'申请部门',
            align:"center",
            dataIndex: 'proposerDeptId_dictText',
            ellipsis: true
          },
          {
            title:'费用所属团队',
            align:"center",
            dataIndex: 'teamId_dictText',
            ellipsis: true
          },
          {
            title:'报销金额（元）',
            align:"center",
            dataIndex: 'reimbursementAmount',
            ellipsis: true
          }
        ],
        columns2: [
        {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'单据编号',
            align:"center",
            dataIndex: 'billNo',
            scopedSlots: { customRender: 'billNo' },
            ellipsis: true
          },
          {
            title:'报销人',
            align:"center",
            dataIndex: 'proposerName',
            ellipsis: true
          },
          {
            title:'申请部门',
            align:"center",
            dataIndex: 'proposerDeptId_dictText',
            ellipsis: true
          },
          {
            title:'费用所属团队',
            align:"center",
            dataIndex: 'teamId_dictText',
            ellipsis: true
          },
          {
            title:'报销金额（元）',
            align:"center",
            dataIndex: 'reimbursementAmount',
            ellipsis: true
          }
        ],
        columns3: [
        {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'单据编号',
            align:"center",
            dataIndex: 'billNo',
            scopedSlots: { customRender: 'billNo' },
            ellipsis: true
          },
          {
            title:'报销人',
            align:"center",
            dataIndex: 'proposerName',
            ellipsis: true
          },
          {
            title:'申请部门',
            align:"center",
            dataIndex: 'proposerDeptId_dictText',
            ellipsis: true
          },
          {
            title:'费用所属团队',
            align:"center",
            dataIndex: 'teamId_dictText',
            ellipsis: true
          },
          {
            title:'报销金额（元）',
            align:"center",
            dataIndex: 'reimbursementAmount',
            ellipsis: true
          }
        ],
        columns4: [
        {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'单据编号',
            align:"center",
            dataIndex: 'billNo',
            scopedSlots: { customRender: 'billNo' },
            ellipsis: true
          },
          {
            title:'报销人',
            align:"center",
            dataIndex: 'proposerName',
            ellipsis: true
          },
          {
            title:'申请部门',
            align:"center",
            dataIndex: 'proposerDeptId_dictText',
            ellipsis: true
          },
          {
            title:'费用所属团队',
            align:"center",
            dataIndex: 'teamId_dictText',
            ellipsis: true
          },
          {
            title:'报销金额（元）',
            align:"center",
            dataIndex: 'reimbursementAmount',
            ellipsis: true
          }
        ],
        url: {
          exportXlsUrl:"/api/erp/project/report/erpProjectFinanceReimbursementReport/exportXls",
          list: '/api/erp/project/report/erpProjectFinanceReimbursementReport/list',
          sum: '/api/erp/project/report/erpProjectFinanceReimbursementReport/getSumGroupBil',
        },
        visible: false,
        travelSum: 0,
        engineeringSum: 0,
        otherSum: 0,
        extractionSum: 0,
        projectId: ''
      }
    },
    created() {
      this.loadData1(1);
      this.loadData2(1);
      this.loadData3(1);
      // 该方法触发屏幕自适应
      this.resetScreenSize();
      this.refresh();
      // 加载数据字典信息
      this.initDictConfig();
    },
    computed: {
    },
    methods: {
      handleExportXls(fileName) {
      this.exportLoading = true
      if (!fileName || typeof fileName !== 'string') {
        fileName = '导出文件'
      }
      let params = {
          projectId: this.projectId
        };
      downFile(this.url.exportXlsUrl, params).then(data => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(
            new Blob([data], {
              type: 'application/vnd.ms-excel'
            }),
            fileName + '.xls'
          )
        } else {
          let url = window.URL.createObjectURL(
            new Blob([data], {
              type: 'application/vnd.ms-excel'
            })
          )
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      }).finally(()=>{
        this.exportLoading = false
      })
    },
      onDetail(record) {
        if(record.billType=='3'){ // 差旅费报销
          this.$refs.traveReimbursementBill.initData(record.id);
          this.$refs.traveReimbursementBill.visible = true;
        }else if(record.billType=='2'){ // 工程进度付款
          this.$refs.projectProgressBill.initData(record.id);
          this.$refs.projectProgressBill.visible = true;
        }else if(record.billType=='1'){ // 其他费用报销
          this.$refs.reimbursementBill.initData(record.id);
          this.$refs.reimbursementBill.visible = true;
        }else if (record.billType == '4') {  // 绩效提取单
          this.$refs.erpAchievementsExtraction.initData(record.id);
          this.$refs.erpAchievementsExtraction.visible = true;
        }
      },
      initDictConfig() {
      },
      // 加载表单
      initData(val) {
        this.initClearData();
        this.projectId = val
        this.loadData1(1) // 差旅费报销
        this.loadData2(1) // 工程进度付款
        this.loadData3(1) // 其他费用报销
        this.loadData4(1)  // 绩效提取单
        this.sumBill()
      },
      initClearData() {
          this.travelSum = 0
          this.engineeringSum = 0
          this.otherSum = 0
          this.extractionSum = 0
      },
      handleCancelDetail() {
        this.visible = true
        this.visibleDetail = false
      },
      sumBill() {
        if (!this.projectId) {
          return
        }
        let params = {
          projectId: this.projectId
        };
        getAction(this.url.sum, params).then(res=>{
          if (res.success) {
            this.mockData = Object.keys(res.result).map(k => {
              if (k === '3') {
                this.travelSum = res.result[k]
              } else if (k === '2') {
                this.engineeringSum = res.result[k]
              } else if (k === '1') {
                this.otherSum = res.result[k]
              } else if (k === '4') {
                this.extractionSum = res.result[k]
              }
            })
          }
        })
      },
      loadData1(arg) {
        if (!this.url.list) {
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination1.current = 1;
        }
        if (!this.projectId) {
          this.dataSource1 = []
          this.ipagination1.total = 0
          return
        }
        let params = {
          projectId: this.projectId,
          billType: '3'
        };
        params.pageNo = this.ipagination1.current;
        params.pageSize = this.ipagination1.pageSize;
        // 查询条件
        var param = Object.assign({}, params, this.isorter, {});
        this.loading1 = true;
        getAction(this.url.list, param).then(res=>{
          if (res.success) {
            this.dataSource1 = res.result.records;
            this.ipagination1.total = res.result.total;
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource1.length === 0 && this.ipagination1.current !== 1) {
              this.ipagination1.current = this.ipagination1.current - 1
              this.loadData(this.ipagination1.current - 1);
            }
          }
        }).finally(() => {
          this.loading1 = false
        })
      },
      loadData2(arg) {
        if (!this.url.list) {
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination2.current = 1;
        }
        if (!this.projectId) {
          this.dataSource2 = []
          this.ipagination2.total = 0
          return
        }
        let params = {
          projectId: this.projectId,
          billType: '2'
        };
        params.pageNo = this.ipagination2.current;
        params.pageSize = this.ipagination2.pageSize;
        var param = Object.assign({}, params, this.isorter, {});
        this.loading2 = true;
        getAction(this.url.list, param).then(res=>{
          if (res.success) {
            this.dataSource2 = res.result.records;
            this.ipagination2.total = res.result.total;
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource2.length === 0 && this.ipagination2.current !== 1) {
              this.ipagination2.current = this.ipagination2.current - 1
              this.loadData2(this.ipagination2.current - 1);
            }
          }
        }).finally(() => {
          this.loading2 = false
        })
      },
      loadData3(arg) {
        if (!this.url.list) {
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination3.current = 1;
        }
        if (!this.projectId) {
          this.dataSource3 = []
          this.ipagination3.total = 0
          return
        }
        let params = {
          projectId: this.projectId,
          billType: '1',
        };
        params.pageNo = this.ipagination3.current;
        params.pageSize = this.ipagination3.pageSize;
        var param = Object.assign({}, params, this.isorter, {});
        this.loading3 = true;
        getAction(this.url.list, param).then(res=>{
          if (res.success) {
            this.dataSource3 = res.result.records;
            this.ipagination3.total = res.result.total;
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource3.length === 0 && this.ipagination3.current !== 1) {
              this.ipagination3.current = this.ipagination3.current - 1
              this.loadData3(this.ipagination3.current - 1);
            }
          }
        }).finally(() => {
          this.loading3 = false
        })
      },
      loadData4(arg) {
        if (!this.url.list) {
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination4.current = 1;
        }
        if (!this.projectId) {
          this.dataSource4 = []
          this.ipagination4.total = 0
          return
        }
        let params = {
          projectId: this.projectId,
          billType: '4'
        };
        params.pageNo = this.ipagination4.current;
        params.pageSize = this.ipagination4.pageSize;
        var param = Object.assign({}, params, this.isorter, {});
        this.loading4 = true;
        getAction(this.url.list, param).then(res=>{
          if (res.success) {
            this.dataSource4 = res.result.records;
            this.ipagination4.total = res.result.total;
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource4.length === 0 && this.ipagination4.current !== 1) {
              this.ipagination4.current = this.ipagination4.current - 1
              this.loadData3(this.ipagination4.current - 1);
            }
          }
        }).finally(() => {
          this.loading4 = false
        })
      },
      handleTableChange1(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
        this.filters = {}
        if (Object.keys(filters).length > 0) {
          for (let key in filters) {
            let value = filters[key].join(',')
            if (value) {
              if (key.indexOf('_dictText') != -1) {
                key = key.substring(0, key.indexOf('_dictText'))
              }
              this.filters[key] = value
            }
          }
        }
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        }
        this.ipagination1 = pagination
        this.loadData1()
      },
      handleTableChange2(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
        this.filters = {}
        if (Object.keys(filters).length > 0) {
          for (let key in filters) {
            let value = filters[key].join(',')
            if (value) {
              if (key.indexOf('_dictText') != -1) {
                key = key.substring(0, key.indexOf('_dictText'))
              }
              this.filters[key] = value
            }
          }
        }
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        }
        this.ipagination2 = pagination
        this.loadData2()
      },
      handleTableChange3(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
        this.filters = {}
        if (Object.keys(filters).length > 0) {
          for (let key in filters) {
            let value = filters[key].join(',')
            if (value) {
              if (key.indexOf('_dictText') != -1) {
                key = key.substring(0, key.indexOf('_dictText'))
              }
              this.filters[key] = value
            }
          }
        }
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        }
        this.ipagination3 = pagination
        this.loadData3()
      },
      handleTableChange4(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
        this.filters = {}
        if (Object.keys(filters).length > 0) {
          for (let key in filters) {
            let value = filters[key].join(',')
            if (value) {
              if (key.indexOf('_dictText') != -1) {
                key = key.substring(0, key.indexOf('_dictText'))
              }
              this.filters[key] = value
            }
          }
        }
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        }
        this.ipagination4 = pagination
        this.loadData4()
      },
      getQueryParams() {
        let param = Object.assign({}, this.queryParam, this.isorter);
        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        return filterObj(param);
      },
      getQueryField() {
        let str = 'id,';
        for (let a = 0; a < this.columns.length; a++) {
          str += ',' + this.columns[a].dataIndex;
        }
        return str;
      },
      searchReset() {
        this.createTime = []
        let that = this;
        Object.keys(that.queryParam).forEach(function (key) {
          that.queryParam[key] = null;
        });
        that.loadData(1);
      },
      searchByquery() {
        this.loadData(1);
      },
      refresh() {
        this.loading1 = true
        this.loading2 = true
        this.loading3 = true
        this.loading4 = true
      },
      open(record) {
        console.log(record);
        this.loadData(1);
      },
      // 触发屏幕自适应
      resetScreenSize() {
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.scrollTrigger = { x: 800 };
        } else {
          this.scrollTrigger = {};
        }
      },
      handleCancel() {
        this.visible = false;
      },
      handleOk() {
        this.handleCancel();
      },
    }
  }
</script>
<style scoped>
  .ant-card-body .table-operator {
    margin-bottom: 18px;
  }

  .ant-table-tbody .ant-table-row td {
    padding-top: 15px;
    padding-bottom: 15px;
  }

  .anty-row-operator button {
    margin: 0 5px
  }

  .ant-btn-danger {
    background-color: #ffffff
  }

  .ant-modal-cust-warp {
    height: 100%
  }

  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto
  }

  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden
  }

  .anty-img-wrap {
    height: 25px;
    position: relative;
  }

  .anty-img-wrap > img {
    max-height: 100%;
  }

</style>